package com.hzw.saas.service.banner.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzw.saas.api.banner.IBannerService;
import com.hzw.saas.api.banner.bo.BannerBo;
import com.hzw.saas.api.banner.dto.BannerDto;
import com.hzw.saas.common.config.util.PageParam;
import com.hzw.saas.common.config.util.PageUtils;
import com.hzw.saas.common.util.MapperUtil;
import com.hzw.saas.common.util.SnowFlakeUtil;
import com.hzw.saas.service.banner.mapper.BannerMapper;
import com.hzw.saas.service.banner.model.Banner;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements IBannerService, IService<Banner> {
    @Override
    @SuppressWarnings("all")
    public BannerDto getBannerList(String clientType) {
        List<Banner> banners = super.lambdaQuery()
                .eq(Banner::getClientType, clientType)
                .list();
        List bannerBos = MapperUtil.nf().mapAsList(banners, BannerBo.class);
        bannerBos.add("$default");
        BannerDto bannerDto = new BannerDto();
        bannerDto.setInterval(CollectionUtils.isEmpty(banners) ? 3000 : banners.get(0).getInterval());
        bannerDto.setUrls(bannerBos);
        return bannerDto;
    }

    @Override
    public Boolean addOrUpdateBanner(BannerBo bannerBo) {
        Banner banner = MapperUtil.nf().map(bannerBo, Banner.class);
        if (StrUtil.isNotBlank(banner.getPid())) {
            // 更新
            return super.updateById(banner);
        } else {
            // 新增
            banner.setPid(SnowFlakeUtil.nextIdStr());
            return super.save(banner);
        }
    }

    @Override
    public IPage<BannerBo> getBanner(String clientType, PageParam pageParam) {
        Page<Banner> bannerPage = super.lambdaQuery()
                .eq(StrUtil.isNotBlank(clientType), Banner::getClientType, clientType)
                .orderByAsc(Banner::getSort)
                .page(pageParam.convert());
        return PageUtils.convert(bannerPage, BannerBo.class);
    }

    @Override
    public Boolean deleteBanner(String pid) {
        return super.removeById(pid);
    }
}
